﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace OpenWaves.EPiServer.Localization.Model
{
    public class TranslationModel
    {
        private readonly List<LangFileEntry> entries = new List<LangFileEntry>();


        public TranslationModel(XDocument document)
        {
            if (document.Root == null)
            {
                throw new ArgumentException("Root element not found", "document");
            }

            this.EPiServerVersion = 7;

            var languageElement = document.Root.Elements("language").First();
            foreach (var element in languageElement.Elements())
            {
                this.entries.Add(this.BuildEntry(element, null));
            }
        }

        public IList<LangFileEntry> Entries
        {
            get { return entries; }
        }

        public int EPiServerVersion { get; set; }

        public LangFileEntry BuildEntry(XElement element, LangFileEntry parent)
        {
            var entry = new LangFileEntry(element.Name.LocalName, parent);
            entry.InitializeWithXElement(element);

            foreach (var subElement in element.Elements())
            {
                entry.Entries.Add(this.BuildEntry(subElement, entry));
            }

            return entry;
        }

        public static TranslationModel FromFiles(IEnumerable<string> filePaths)
        {
            var documents = filePaths.Select(XDocument.Load).ToArray();
            if (documents.Length == 0)
            {
                throw new InvalidOperationException("No language files found");
            }
            var merged = LanguageXmlMerge.Merge(documents);
            return new TranslationModel(merged);
        }
    }
}